from flask import render_template,request,url_for,flash
from ..models import *
from . import admin
from .. import db,UP_DIR
from .forms import optionalForm
from werkzeug.utils import secure_filename
import os,uuid

def gen_rnd_filename():
    return datetime.now().strftime("%Y%m%d%H%M%S") + str(uuid.uuid4().hex)

def change_filename(filename):
    """
    修改文件名称
    """
    fileinfo = os.path.splitext(filename)
    filename =  gen_rnd_filename() + fileinfo[-1]
    return filename

@admin.route("/")
def index():
    return render_template('admin/index.html')

@admin.route("/login",methods=["GET","POST"])
def login():
    if request.method == "GET":
        return "login_page"
    else:
        pass

@admin.route("/menus")
def menu_view():
    page = request.args.get('page', 1, type=int)
    page_data = Optionalfood.query.order_by(
            Optionalfood.id.desc()
        ).paginate(page=page, per_page=5)
    return render_template('admin/menu.html',page_data=page_data)

@admin.route("/addmenu",methods=["GET","POST"])
def addmenu():
    form = optionalForm()
    if form.validate_on_submit():

        file_images = secure_filename(form.images.data.filename)
        if not os.path.exists(UP_DIR):
            os.makedirs(UP_DIR)           
            os.chmod(UP_DIR,'rw')
        imagesname = change_filename(file_images)
        form.images.data.save(UP_DIR + imagesname)

        food = Optionalfood()
        food.cname = form.data['cname']
        food.cprice = form.data['cprice']
        food.ingredients = form.data['ingredients']
        food.mealmeans = form.data['mealmeans']
        food.points = form.data['points']
        food.stock = form.data['stock']
        food.taste = form.data['taste']
        food.type = form.data['type']
        food.images = 'images/'+imagesname

        db.session.add(food)
        db.session.commit()
        flash('添加成功!','ok')
        
    return render_template('admin/addmenu.html',form=form)

@admin.route("/menus/edit/<food_id>",methods=['GET','POST'])
def menus_edit(food_id):
    form = optionalForm()
    form.submit.label.text = '修改'
    form.images.validators = []
    pack = Optionalfood.query.filter_by(id=food_id).first()
    if request.method == "GET":
        form.cname.data = pack.cname
        form.cprice.data = pack.cprice
        form.ingredients.data = pack.ingredients
        form.taste.data = pack.taste
        form.type.data = pack.type
        form.points.data = pack.points
        form.stock.data = pack.stock
        form.mealmeans.data = pack.mealmeans
        form.images.data = pack.images

    if form.validate_on_submit():
        data = form.data
        if not os.path.exists(UP_DIR):
            os.makedirs(UP_DIR)           
            os.chmod(UP_DIR,'rw')
        if form.images.data != "":
            file_images = secure_filename(form.images.data.filename)     
            imagesname = change_filename(file_images)                       
            form.images.data.save(UP_DIR + imagesname)
            pack.images = 'images/'+imagesname
        pack.cname = data['cname']
        pack.cprice = data['cprice']
        pack.ingredients = data['ingredients']
        pack.taste = data['taste']
        pack.type = data['type']
        pack.points = data['points']
        pack.stock = data['stock']
        pack.mealmeans = data['mealmeans']

        db.session.add(pack)
        db.session.commit()
        flash("修改成功!","ok")
        print("ok")
        return render_template("admin/menus_edit.html",form=form)
    return render_template("admin/menus_edit.html",form=form)


